# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/18 18:36 
@Author  : ZhangShenao 
@File    : 2.异步回调函数.py 
@Desc    : 异步回调函数

回调函数本身是一种编程模式,与同步或异步无关
但是实际使用时,回调函数多用于异步方式执行
"""
import asyncio


async def process(a: int, b: int, callback: callable) -> None:
    """异步主执行函数"""

    print('process start...')

    # 模拟异步函数执行
    await asyncio.sleep(1)
    result = a + b

    # 执行回调函数
    callback(result)

    print('process finished...')


async def another_task() -> None:
    """另一个异步任务"""

    print('another task start...')

    # 模拟异步函数执行
    await asyncio.sleep(2)

    print('another task finished...')


def print_result_callback(result: int) -> None:
    """回调函数"""

    print(f'the result is : {result}')


async def run() -> None:
    """运行函数"""

    print('run start...')

    # 创建两个异步任务
    task1 = asyncio.create_task(process(3, 4, print_result_callback))
    task2 = asyncio.create_task(another_task())

    # 等待两个异步任务执行完成
    await asyncio.gather(task1, task2)

    print('run finished...')


if __name__ == '__main__':
    asyncio.run(run())

    # 执行结果:
    # run start...
    # process start...
    # another task start...
    # the result is : 7
    # process finished...
    # another task finished...
    # run finished...
